import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { authGuard } from './guards/auth'

// 自动导入路由模块
const modules = import.meta.glob('./modules/**/*.ts', { eager: true })

// 路由记录
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    name: 'Login',
    meta: { title: '登录', hidden: true },
  },
  {
    path: '/404',
    component: () => import('@/views/404/index.vue'),
    name: 'NotFound',
    meta: { title: '404', hidden: true },
  },
]

// 动态路由
export const asyncRoutes: RouteRecordRaw[] = Object.values(modules).reduce(
  (routes: RouteRecordRaw[], module: any) => {
    if (module.default) {
      return [
        ...routes,
        ...(Array.isArray(module.default) ? module.default : [module.default]),
      ]
    }
    return routes
  },
  [],
)

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

// 注册路由守卫
router.beforeEach(authGuard)

// 重置路由
export function resetRouter() {
  const newRouter = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
    scrollBehavior: () => ({ left: 0, top: 0 }),
  })
  ;(router as any).matcher = (newRouter as any).matcher
}

export default router
